<template>
  <div>
    <canvas ref="myCanvas" width="700" height="600" style="border: 1px solid #000000"></canvas>
  </div>
</template>


<script>
export default {
  name: "shangpinGoods",
  components: {},
  data() {
    return {};
  },
  methods: {},
  created() {},
  mounted() {
    var c = this.$refs.myCanvas;
    var ctx = c.getContext("2d");

    //定义x,y起始位;判定上下左右移动的flag
    var x = 50,
      y = 50,
      radius = 50,
      flag_x = true,
      flag_y = true;

    //添加定时器
    setInterval(function () {
      //flag_x如果为true,起始位向右移动,即x++;反之向左移动;
      if (flag_x) {
        x++;
        if (x > c.offsetWidth - radius) {
          //小球撞到右侧边框后,向左移动;50为小球半径
          flag_x = false;
        }
      } else {
        x--;
        if (x < radius) {
          //小球撞到左侧边框后,向右移动;
          flag_x = true;
        }
      }

      //flag_y如果为true,起始位向下移动,即y++;反之向上移动;
      if (flag_y) {
        y++;
        if (y > c.offsetHeight - radius) {
          //小球撞到下方边框后,向上移动
          flag_y = false;
        }
      } else {
        y--;
        if (y < radius) {
          //小球撞到上边框后,向下移动;
          flag_y = true;
        }
      }

      //绘图前先清除画布
      ctx.clearRect(0, 0, c.offsetWidth, c.offsetHeight);
      //开始绘图
      ctx.beginPath();
      ctx.arc(x, y, radius, 0, Math.PI * 2, true);
      ctx.fillStyle = "#aaaaaa";
      ctx.fill();
    }, 10);
  },
};
</script>

<style>
</style>